<template>
  <el-drawer
    v-model="drawerVisible"
    :destroy-on-close="true"
    size="700px"
    :title="`${drawerProps?.title}菜单`"
    @open="drawerOpen"
  >
    <el-form ref="editRef" :model="form" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="form.roleName" placeholder="请输入部门名称" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="权限字符" prop="roleKey">
            <el-input v-model="form.roleKey" placeholder="请输入部门名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="显示排序" prop="roleSort">
            <el-input-number v-model="form.roleSort" controls-position="right" :min="0" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :label="0">启用</el-radio>
              <el-radio :label="1">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="菜单权限" prop="phone">
            <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
            <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
            <div class="role-menu-tree">
              <el-tree
                class="tree-border"
                :data="menuOptions"
                show-checkbox
                ref="menuRef"
                node-key="id"
                empty-text="加载中，请稍候"
                :props="{ label: 'label', children: 'children' }"
              ></el-tree>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="form.remark" controls-position="right" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false"> 取消 </el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="EditDrawer">
import { ref, reactive, toRefs, getCurrentInstance, ComponentInternalInstance } from "vue";
import SelectIcon from "@/components/SelectIcon/index.vue";
import { ElMessage, FormInstance } from "element-plus";
import { handleTree } from "@/utils";
import { SystemApi, MenuApi } from "@/api/modules";
import { IRole } from "./role.interface";
import { nextTick } from "vue";
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<IRole>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}
const menuOptions = ref<any[]>([]);
const drawerVisible = ref(false);
const showChooseIcon = ref(false);
const iconSelectRef = ref<any>(null);
const data = reactive<{
  form: any;
  queryParams: any;
  rules: any;
}>({
  form: {
    roleId: undefined,
    roleKey: "",
    roleSort: 1,
    roleName: "",
    status: 0,
    menuIds: [],
    remark: undefined,
  },
  queryParams: {
    deptName: undefined,
    visible: undefined,
  },
  rules: {
    roleName: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  },
});
const menuRef = ref(null);
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {},
});
const { queryParams, form, rules } = toRefs(data);

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  if (Object.getOwnPropertyNames(params.row).length) {
    if (params.title == "编辑") {
      data.form = JSON.parse(JSON.stringify(params.row));
    }
    if (params.title == "新增") {
      data.form = {
        roleKey: "",
        roleSort: 1,
        roleName: "",
        status: 0,
        roleId: undefined,
        menuIds: [],
        remark: undefined,
      };
    }
  } else {
    data.form = {
      roleId: undefined,
      roleKey: "",
      roleSort: 1,
      roleName: "",
      status: 0,
      menuIds: [],
      remark: undefined,
    };
  }

  drawerVisible.value = true;
};
// drawer 打开时的事件
const drawerOpen = () => {
  getTreeSelect();
  if (data.form.roleId) {
    const roleMenu = getRoleMenuTreeselect(data.form.roleId);
    nextTick(() => {
      roleMenu.then(res => {
        let checkedKeys = res.checkedKeys;

        checkedKeys.forEach(v => {
          nextTick(() => {
            menuRef.value.setChecked(v, true, false);
          });
        });
      });
    });
  }
};
// 提交数据（新增/编辑）

const handleSubmit = () => {
  (proxy?.$refs["editRef"] as any).validate(async (valid: any) => {
    if (!valid) return;
    try {
      const payload = JSON.parse(JSON.stringify(data.form));
      payload.menuIds = getMenuAllCheckedKeys();
      await drawerProps.value.api(payload);
      await ElMessage.success({ message: `${drawerProps.value.title}成功！` });
      drawerVisible.value = false;
      drawerProps.value.getTableList!();
    } catch (error) {
      console.log(error);
    }
  });
  function getMenuAllCheckedKeys() {
    // 目前被选中的菜单节点
    let checkedKeys = menuRef.value.getCheckedKeys();
    // 半选中的菜单节点
    let halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
    checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
    return checkedKeys;
  }
  // ruleFormRef.value!.validate(async valid => {
  //   if (!valid) return;
  //   try {
  //     await drawerProps.value.api!(drawerProps.value.row);
  //     ElMessage.success({ message: `${drawerProps.value.title}用户成功！` });
  //     drawerProps.value.getTableList!();
  //     drawerVisible.value = false;
  //   } catch (error) {
  //     console.log(error);
  //   }
  // });
};
const getTreeSelect = async () => {
  menuOptions.value = [];
  let res: any = await MenuApi.getMenuTreeSelect();
  menuOptions.value = res.data;
};
function handleCheckedTreeExpand(value, type: string) {
  if (type == "menu") {
    let treeList = menuOptions.value;
    for (let i = 0; i < treeList.length; i++) {
      menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
    }
  }
}
function handleCheckedTreeNodeAll(value, type) {
  if (type == "menu") {
    menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
  }
}
function getRoleMenuTreeselect(roleId) {
  return MenuApi.roleMenuTreeselect(roleId).then((response: any) => {
    menuOptions.value = response.menus;

    return response;
  });
}
defineExpose({
  acceptParams,
});
</script>

<style lang="scss" scoped>
.role-menu-tree {
  width: 100%;
  max-height: 400px;
  padding: 10px;
  overflow: auto;
  border: 1px solid #dddddd;
  border-radius: 4px;
}
</style>
